package ch14_反射与注解.成员信息;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

/**
 * @author 挚爱之夕
 * @date 2021/8/29 - 08 - 29 - 9:34
 * @Description: ch14_反射与注解.成员信息
 * @Version: 1.0
 */
enum BookKind { //图书种类
    COMPUTER,MATH,ENGLISH
};

class Book{
    double price = 20;
    String[] authors = {"Daniel","Jack"};
    BookKind kind = BookKind.COMPUTER;
}
public class FieldDemo {
    public static void main(String[] args) {
        Book book = new Book();
        Class<?> cls = book.getClass();

        try{
            /*通过名称获得各字段*/
            Field price = cls.getDeclaredField("price");
            Field authors = cls.getDeclaredField("authors");
            Field kind = cls.getDeclaredField("kind");

            System.out.printf("%-35s%s\n","Before","After");
            for (int i = 0; i < 62; i++) {
                System.out.print("-");
            }

            /*通过反射机制获得并修改各字段的值*/
            System.out.printf("\n%-8s = %-24s",price.getName(),price.getDouble(book));//book类中price字段的值
            price.setDouble(book,30);//设置book类中price的值为30
            System.out.printf("%-8s = %-24s\n","price",book.price);

            List<String> authorList = Arrays.asList((String[]) authors.get(book));//得到book类中author的值封装为list
            System.out.printf("%-8s = %-24s",authors.getName(),authorList);
            String[] newAuthors = {"Andy","Joe","Tom"};
            authors.set(book,newAuthors);
            System.out.printf("%-8s = %-24s\n","author",Arrays.asList(book.authors));

            System.out.printf("%-8s = %-24s",kind.getName(),(BookKind) kind.get(book));
            kind.set(book,BookKind.MATH);//设置book类中kind字段
            System.out.printf("%-8s = %-24s\n","Kind",book.kind);
        }catch (NoSuchFieldException e){//由getDeclaredField方法抛出
            System.out.println("找不到名为："+e.getMessage()+"的字段");
        }catch (IllegalAccessException e){//由get/set字段值的方法抛出
            System.out.println("字段不可访问。");
        }
    }
}
